import os
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import requests
import json
import sqliteOperation

app = Flask(__name__)
CORS(app)  # 跨域专用，勿删


@app.before_request
def init_sqliteDB():
    if not os.path.exists(sqliteOperation.db_name):
        sqliteOperation.init_sqlite()


@app.route("/insert", methods=["GET"])
def insert():
    # ip_address, device_info, location
    ip_address = request.args.get("ip_address")
    device_info = request.args.get("device_info")
    location = request.args.get("location")
    if not ip_address or not device_info or not location:
        return "Please provide a  parameter."
    return sqliteOperation.INSERT(ip_address, device_info, location)


@app.route("/delete", methods=["GET"])
def delete():
    return sqliteOperation.DELETE()


@app.route("/update", methods=["GET"])
def update():
    return sqliteOperation.UPDATE()


@app.route("/select", methods=["GET"])
def select():
    return sqliteOperation.SELECT()


@app.route("/addone", methods=["GET"])
def addone():
    # 文件名
    filename = "visitorCount.txt"

    # 步骤1和2：读取文件中的整数
    try:
        with open(filename, "r") as file:
            number = int(file.read().strip())  # 读取文件内容并转换为整数
    except ValueError:
        print("文件中没有有效的整数，或者文件格式不正确。")
        exit()

        # 对整数加1
    number += 1

    # 步骤4、5和6：将加1后的整数写回文件
    try:
        with open(filename, "w") as file:
            file.write(
                str(number) + "\n"
            )  # 写入加1后的整数并添加一个换行符（如果需要）
    except IOError as e:
        print(f"无法写入文件: {e}")
        exit()

    print(f"整数已加1并保存回文件：{number}")
    return str(number)


# https://qt.gtimg.cn/q=sh000001
@app.route("/sh000001", methods=["GET"])
def sh000001():
    url = "https://qt.gtimg.cn/q=sh000001"
    try:
        response = requests.get(url, timeout=10)
        data_bytes = response.content
        data_str = data_bytes.decode("utf-8", errors="ignore")
        cleaned_data = data_str.strip('"').replace('v_sh000001="', "")
        fields = cleaned_data.split("~")
        target_value = fields[3]
        return str(target_value)

    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误


# https://qt.gtimg.cn/q=sh000300
@app.route("/sh000300", methods=["GET"])
def sh000300():
    url = "https://qt.gtimg.cn/q=sh000300"
    try:
        response = requests.get(url, timeout=10)
        data_bytes = response.content
        data_str = data_bytes.decode("utf-8", errors="ignore")
        cleaned_data = data_str.strip('"').replace('v_sh000300="', "")
        fields = cleaned_data.split("~")
        target_value = fields[3]
        return str(target_value)

    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误


# https://blockchain.info/ticker
@app.route("/btcprice", methods=["GET"])
def btcprice():
    url = "https://blockchain.info/ticker"
    try:
        response = requests.get(url, timeout=10)
        data_bytes = response.content
        # 将字节字符串解码为普通字符串
        data_str = data_bytes.decode("utf-8")
        # 使用json.loads()方法将字符串解析为Python字典
        data_dict = json.loads(data_str)
        # 现在，data_dict是一个包含所有货币信息的字典
        # 您可以像这样访问数据
        usd_last = data_dict["USD"]["15m"]
        # 您可以打印出来看看
        return str(usd_last)
    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误
    
# https://v2.xxapi.cn/api/allrates
@app.route("/rmbtousd", methods=["GET"])
def rmbtousd():
    url = "https://v2.xxapi.cn/api/allrates"
    try:
        payload = {}
        headers = {
        'User-Agent': 'xiaoxiaoapi/1.0.0 (https://xxapi.cn)'
        }
        response = requests.request("GET", url, headers = headers, data = payload)
        data = json.loads(response.text)
        cny_rate = data['data']['rates']['CNY']['rate']
        print(cny_rate)
        return str(round(cny_rate, 3))
    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误     
    
    # https://v2.xxapi.cn/api/allrates
@app.route("/au9999", methods=["GET"])
def au9999():
    url = "https://api.pearktrue.cn/api/goldprice/"
    try:
        price=0
        response = requests.request("GET", url)
        response_data = json.loads(response.text)
        for item in response_data["data"]:
            if item["dir"] == "au9999":
                price = item["price"]
                price=price
                break
        print(price)
        return str(price)
    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误     



# http://api-screeps.mofengfeng.com/api/portals/find_route?from=shard0_W1N1&to=shard3_W2N2
@app.route("/find_route", methods=["GET"])
def find_route():
    url = "http://api-screeps.mofengfeng.com/api/portals/find_route?"
    param_from = request.args.get("from")
    param_to = request.args.get("to")
    if not param_from or not param_to:
        return "Please provide a URL parameter."
    get_request = url + "from=" + param_from + "&to=" + param_to
    # get_request = 'http://api-screeps.mofengfeng.com/api/portals/find_route?from=shard0_W1N1&to=shard3_W2N2'
    try:
        response = requests.get(get_request, timeout=10)
        return response.content
    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误


@app.route("/checkurl_post", methods=["POST"])
def checkurl_post():
    # 获取 JSON 数据
    data = request.get_json()
    print(data)
    # 初始化结果字典
    results = {}

    # 遍历数据并发送 GET 请求
    for key, value in data.items():
        href = value["href"]
        try:
            # 发送 GET 请求并获取状态码
            response = requests.get(href, timeout=5)  # 设置超时时间以避免长时间等待
            results[key] = {"state_code": response.status_code}
        except requests.exceptions.RequestException as e:
            # 如果发生异常（例如，超时、连接错误等），记录错误
            results[key] = {"error": str(e)}
    print(results)
    # 返回结果
    return jsonify(results)


@app.route("/checkurl", methods=["GET"])
def checkurl():
    url_param = request.args.get("url")
    if not url_param:
        return jsonify(
            {"url": url_param, "status_code": "Please provide a URL parameter."}
        )
    try:
        response = requests.get(url_param, timeout=10)
        status_code = response.status_code
        return jsonify({"url": url_param, "status_code": status_code})
    except requests.exceptions.ConnectionError as e:
        return (
            jsonify({"error": "连接错误: " + str(e)}),
            503,
        )  # 503是HTTP状态码，表示服务不可用
    except requests.exceptions.Timeout as e:
        return (
            jsonify({"error": "请求超时: " + str(e)}),
            504,
        )  # 504是HTTP状态码，表示网关超时
    except requests.exceptions.RequestException as e:
        return (
            jsonify({"error": "网关错误: " + str(e)}),
            502,
        )  # 502是HTTP状态码，表示网关错误


@app.route("/")
def main():
    # 使用字典来存储API的描述和URL
    apis = {
        "url_status_check": {
            "api": "URL状态码查询",
            "url": "https://api.zsuuu.com/checkurl?url=https://www.zsuuu.com",
        },
        "mofeng_find_route": {
            "api": "Mofeng星门寻路(https转发)",
            "url": "https://api.zsuuu.com/find_route?from=shard0_W1N1&to=shard3_W2N2",
        },
        "btc_price": {"api": "BTC实时价格", "url": "https://api.zsuuu.com/btcprice"},
        "usd_price": {"api": "美元实时价格", "url": "https://api.zsuuu.com/rmbtousd"},
        "hsi_index": {"api": "沪深300指数", "url": "https://api.zsuuu.com/sh000300"},
        "au9999": {"api": "黄金实时价格", "url": "https://api.zsuuu.com/au9999"},
        "shangzheng_index": {
            "api": "上证指数",
            "url": "https://api.zsuuu.com/sh000001",
        },
        "database_read": {"api": "数据库读取", "url": "https://api.zsuuu.com/select"},
    }
    # 将apis字典传递给模板
    return render_template("index.html", apis=apis)


if __name__ == "__main__":
    sqliteOperation.init_sqlite()
    app.run(host="0.0.0.0", port=20444)
